<template>
  <div class="container">
    <Navbars ></Navbars>
    <!-- 条件 -->
    <div class="querydiv" shadow="never">
      <el-form :inline="true" size="medium" label-width="70px">
        <el-form-item label="">
          <el-input v-model="listQuery.name" placeholder="角色名称"></el-input>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="listQuery.code" placeholder="角色编码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button class="btn btncolor" type="primary" @click="getList">查询</el-button>
          <el-button class="btn" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格 -->
    <div class="mt15">
      <el-card class="tab-card" shadow="never">
        <div slot="header" class="spacebetween disflex align-center">
          <span style="color:#676a6f;font-size:14px">角色列表</span>
          <el-button class="btn btncolor" icon="el-icon-plus" type="primary" @click="handleAdd">新增</el-button>
        </div>
        <el-table :data="list" :header-cell-style="{background:'#e4ebfd',color:'#7690db'}" :row-class-name="tableRowClassName">
            <el-table-column align="center" prop="name"  label="角色名称" ></el-table-column>
            <el-table-column align="center" prop="code" label="角色编码"></el-table-column>
            <el-table-column align="center" prop="status" label="角色状态"></el-table-column>
            <el-table-column align="center" prop="createTime" label="创建时间"></el-table-column>
            <el-table-column align="center" prop="remarks" label="备注"></el-table-column>
            <el-table-column align="center" fixed="right"  label="操作">
              <template slot-scope="scope">
                <el-button type="text"  class="edit" @click="handlEdit(scope.row)">编辑</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" @click="handleRules(scope.row)">分配权限</el-button>
                <el-divider direction="vertical"></el-divider>
                <el-button type="text" @click="handleDelete(scope.row)" class="del">删除</el-button>
              </template>
          </el-table-column>
        </el-table>
      </el-card>
      <!--分页 -->
      <Pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.num"></Pagination>
    </div>
    <!-- 新增修改弹窗 -->
    <el-dialog :title="title" :visible.sync="is_add_role" width="40%" :close-on-click-modal="false">
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="addForm.code"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="addForm.remarks"></el-input>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-radio-group v-model="addForm.status" size="small">
            <el-radio-button v-for="(item,index) in statuslist" :key="index" :label="item.code">{{item.name}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitAdd" size="small" :loading="loading" :disabled="loading">确定</el-button>
          <el-button size="small" @click="is_add_role = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限菜单 -->
    <el-dialog title="分配权限菜单" :visible.sync="menuvisible" width="40%" :close-on-click-modal="false">
      <el-form
      
        label-width="80px"
      >
        <el-form-item label="角色权限" prop="name">
          <el-tree
            :data="menuTreelsit"
            show-checkbox
            node-key="id"
            :props="defaultProps"
            ref="addMenuTree"
          ></el-tree>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitMenu" :loading="loading" :disabled="loading">确定</el-button>
          <el-button @click="menuvisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    
    
  </div>
</template>

<script>
import {
  roleList,
  roleAdd,
  dicttype,
  roleDetail,
  roleEdit,
  delRole,
  getAllocation,
  allocation
} from "@/api/role.js";
import { menuList } from "@/api/menu.js"
import Pagination from "@/components/Pagination";
import {formatDataTree} from '@/utils/index'
export default {
  name: "role",
  components: { Pagination },
  data() {
    return {
      title:'新增角色',
      list: null,
      total: 0,
      is_add_role: false,
      listLoading: true,
      loading:false,
      listQuery: {
        page: 1,
        num: 20,
        name:"",
        code:"",
        status:''
      },
      statuslist :[],
      menuTreelsit: [],
      menuvisible:false,
      defaultProps: {
        label: "name",
        children: "children",
      },
      Menufrom:{
        roleId:'',
        menuId:[]
      },
      count: 1,
      addForm: {
        name: "",
        code: "",
        status: "",
        remarks:''
      },
      addRules: {
        name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入编码", trigger: "blur" }],
      },
      editForm: {
        roleId: 0,
        roleName: "",
        roleCode: "",
        roleStatus: "",
        menus: [],
      },
      editRules: {
        roleName: [{ required: true, message: "请输入账号", trigger: "blur" }],
        roleCode: [{ required: true, message: "请输入编码", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getDIctyp()
    this.getMenuTree();
  },
  methods: {
    // 设置表格颜色
    tableRowClassName({row, rowIndex}) {
      if (rowIndex%2==0) { return 'warning-row'}
      return '';
    },
    // 新增弹窗
    handleAdd(){
      this.is_add_role = true
      this.title = "新增角色"
    },
    // 获取状态字典
    getDIctyp(){
      this.$getFlag().then(obj=>{
        dicttype({type:'role_status'},obj.data).then(res=>{
          if(res.status == 200){
            this.statuslist = res.data
          }
        })
      })
    },
    // 重置
    handleReset(){
      
      
    },

    onSubmitAdd() {
      this.$refs["addForm"].validate((valid) => {
        if (!valid) {
          this.$notify({
            title: "操作失败",
            message: "请正确填写数据",
            type: "error",
            duration: 2000,
          });
          return;
        }
        if(this.title=='新增角色'){
          this.loading=true;
          this.$getFlag().then(obj=>{
            roleAdd(this.addForm,obj.data).then((response) => {
              if (response.status == 200) {
                this.$notify({title: "操作成功", message: "添加成功",  type: "success",  duration: 2000,});
                this.is_add_role = false;
                this.getList();
              } else {
                this.$notify({  title: "操作失败",  message: response.msg,  type: "error",  duration: 2000,});
              }
              this.loading=false;
            })
            .catch(() => {
              this.loading=false;
            });
          })
        }else{
          this.$getFlag().then(obj=>{
            roleEdit(this.addForm,obj.data).then(response=>{
              if (response.status == 200) {
                this.$notify({title: "操作成功", message: "添加成功",  type: "success",  duration: 2000,});
                this.is_add_role = false;
                this.getList();
              } else {
                this.$notify({  title: "操作失败",  message: response.msg,  type: "error",  duration: 2000,});
              }
              this.loading=false;
            })
          })
        }
      });
    },
    // 编辑弹窗
    handlEdit(row){
      this.is_add_role = true
      this.title = "编辑角色"
      this.$getFlag().then(obj=>{
        roleDetail({id:row.id},obj.data).then(res=>{
          if(res.status == 200){
            this.addForm = res.data
          }
        })
      })
    },
    // 表格列表
    getList() {
      this.$getFlag().then(obj=>{
        this.listLoading = false;
        roleList(this.listQuery,obj.data).then((response) => {
          this.list = response.list;
          this.total = Number(response.total);
          setTimeout(() => {
            this.listLoading = false;
          }, 1.5 * 1000);
        });
      })
    },
    // 菜单列表
    getMenuTree(){
      let form = {
        page:1,
        num:100,
        pid:'',
        name:''
      }
      
      this.menuTreelsit = []
      this.$getFlag().then(obj=>{
        menuList(form,obj.data).then(res=>{
          if(res.status == 200){
            this.menuTreelsit.push(formatDataTree(res.list))
          }
        })
      })
    },
    // 分配权限菜单弹窗
    handleRules(row){  
      this.menuvisible = true
      // 获取已分配的菜单
      this.Menufrom.roleId = row.id
      this.$getFlag().then(obj=>{
        getAllocation({id:row.id},obj.data).then(res=>{
          if(res.status == 200){
            this.$refs.addMenuTree.setCheckedKeys([]);
            if (res.data.length > 0) {
              for (var i = 0; i < res.data.length; i++) {
                this.$refs.addMenuTree.setChecked(
                  res.data[i],
                  true,
                  false
                );
              }
            }
          }
        })
      })
    },
    // 确定分配权限
    onSubmitMenu(){
      this.Menufrom.menuId = []
      var checkNodes = this.$refs.addMenuTree.getCheckedNodes(false, true);
        if (checkNodes.length > 0) {
          for (var i = 0; i < checkNodes.length; i++) {
            this.Menufrom.menuId.push(checkNodes[i].id);
          }
        }
      this.$getFlag().then(obj=>{
        allocation(this.Menufrom,obj.data).then(res=>{
          if(res.status == 200){
            this.$notify({  title: "操作成功", message: res.msg, type: "success",duration: 2000,});
            this.menuvisible = false
          }else{
            this.$notify({ title: "操作失败",message: res.error, type: "error", duration: 2000,});
          }
        })
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm("确定要删除角色吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$getFlag().then(obj=>{
          delRole({id:row.id},obj.data).then((response) => {
            if (response.status == 200) {
              this.$notify({
                title: "操作成功",
                message: response.msg,
                type: "success",
                duration: 2000,
              });
              this.getList();
            } else {
              this.$notify({
                title: "操作失败",
                message: response.msg,
                type: "error",
                duration: 2000,
              });
            }
          });
        }) 
        }).catch(() => {
          //
        });
    },
  },
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}

</style>
<style>
  .el-table .warning-row {
    background: #f6f9fe;
  }
</style>
